'''
Created on 2014-4-20

@author: shen
'''
import urllib
import simplejson as json
from ASIN import get_ASIN

REQUEST_URL = 'http://112.124.1.3:8004/api/commodity'

def category_name():
#    return 'Clothing $ Accessories>Women>Jeans'
    return 'Cell Phones $ Accessories>Cell Phones>Contract Cell Phones'


class Get_price_trend:
    def write_info(self , ASIN):
        list = []
    
        #take info of page i
        specified_cate_data = json.loads(urllib.urlopen('?'.join(['/'.join([REQUEST_URL,ASIN]),
            urllib.urlencode({
            'field': ['offer'],
            })])).read())
        
        list = specified_cate_data['offer']
        
        price_time_seller_list = [];
        
        for item in list:
            if len(item['info'])>0:
                price_time_seller = {u'time':item['timestamp'] , u'price':item['info'][0]['price'] , u'seller':item['info'][0]['seller']['name']}
                if price_time_seller['price']!=0.0:
                    price_time_seller_list.append(price_time_seller)
        
#        the construction of price_time_seller_list:time , price , seller
        
        return price_time_seller_list
    
def count(category):
    count = json.loads(urllib.urlopen('?'.join(['http://112.124.1.3:8004/api/commodity/count/',
            urllib.urlencode({
            'category_name': category})])).read())
    return count
    
    
    #write the info into txt file
if __name__ == '__main__':
    #   20 record in a page , from page 0 to page end
    category = category_name()
    
    count = count(category)['count']
    
    print count
    
    get_data = True
    
    if get_data==False:
        quit()
    
    end_page = count/20+1
    print end_page
    
    g = get_ASIN()
    ASIN_list = []
    for i in range(0,end_page):
        ASIN_list.extend(g.write_info(category,i))
        
    info_list = []

    g2 = Get_price_trend()
    
    for item in ASIN_list:    
        item = {u'ASIN':item , u'price_seller_time_list':g2.write_info(item)}
        if len(item['price_seller_time_list'])!=0:
            info_list.append(item)
        
    # write to the file
    f = file('txt_package_phone_price.txt', 'w') # open for 'w'riting
    for item in info_list:
        ASIN = item['ASIN']
        f.write(ASIN+'\n') # write text to file
        price_seller_time_list = item['price_seller_time_list']
        for item2 in price_seller_time_list:
            price = item2['price']
            seller = item2['seller']
            time = item2['time']
            f.write('    '+str(price)+'    '+str(seller)+'    '+str(time)+'\n')
    
    f.close() # close the file